package com.baihang.platform.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baihang.framework.controller.BaseController;
import com.baihang.framework.kit.HashKit;
import com.baihang.framework.kit.ShiroKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.platform.service.IndexService;

@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

	// private static Log log= LogFactory.getLog(IndexController.class);
	private static Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private IndexService service;

	@RequestMapping
	public String index(Model model) {
		String realName = ShiroKit.getCurrentUser().getRealName();
		model.addAttribute("name", realName);
		model.addAttribute("menus",service.getMenuTree());
		return "index";
	}

	@GetMapping("/login")
	public String login() {
		logger.info("123123");
		System.err.println("login");
		return "login";
	}

	@PostMapping("/login")
	public String login(String userName, String password, Model model) {
		logger.warn("用户名{},密码{}", userName, password);
		// 判断是否在做登录操作
		if (StrKit.isNotEmpty(userName, password)) {
			try {
				SecurityUtils.getSubject().login(
						new UsernamePasswordToken(userName, HashKit.md5(password).toUpperCase(), false, "localhost"));			
			} catch (AuthenticationException e) {
				model.addAttribute("errorMsg", "帐号或密码有误!");
				System.err.println(e.getMessage());
			}
		}

		if (ShiroKit.isAuthed()) {
			return "redirect:/";
		}
		return "login";
	}

	@RequestMapping("/logout")
	public String logout() {
		ShiroKit.logOut();
		return "redirect:/login";
	}

	@RequestMapping("/unAuthorized")
	public String unAuthorized() {

		return "unAuthorized";
	}
}
